﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ReadyApps.Data.Wiki
{
    /// <summary>
    /// Represents the inheritance hierarchy of permissions.
    /// </summary>
    /// <seealso cref="ObjectPermissionSet"/>
    [Serializable]
    public class PermissionsHierarchy : IEnumerable<ObjectPermissionSet>
    {
        #region Variables and Constants

        private List<ObjectPermissionSet> objectPermissionSets;
        private int activePermissionSetID;

        #endregion

        #region Constructor

        /// <summary>
        /// Creates a new <see cref="PermissionsHierarchy"/> object for the supplied active
        /// permission set ID.
        /// </summary>
        /// <param name="activePermissionSetID">The permission set ID for the active permission
        /// set.</param>
        public PermissionsHierarchy(int activePermissionSetID)
        {
            this.activePermissionSetID = activePermissionSetID;
            objectPermissionSets = new List<ObjectPermissionSet>();
        }

        #endregion

        #region Public Methods

        /// <summary>
        /// Adds an <see cref="ObjectPermissionSet"/> to the end of the hierarchy.
        /// </summary>
        /// <param name="objectPermissionSet">The <see cref="ObjectPermissionSet"/> to add to
        /// the hierarchy.</param>
        public void Add(ObjectPermissionSet objectPermissionSet)
        {
            if (objectPermissionSet.PermissionSetID == activePermissionSetID)
            {
                foreach (var objPermSet in objectPermissionSets.Where(p => p.IsActive))
                {
                    objPermSet.IsActive = false;
                }
                objectPermissionSet.IsActive = true;
            }
            objectPermissionSets.Add(objectPermissionSet);
        }

        #endregion

        #region Interface Methods

        /// <summary>
        /// Gets an <see cref="IEnumerator{ObjectPermissionSet}"/> for the hierarchy.
        /// </summary>
        /// <returns>An <see cref="IEnumerator{ObjectPermissionSet}"/> for the hierarchy.</returns>
        public IEnumerator<ObjectPermissionSet> GetEnumerator()
        {
            return objectPermissionSets.GetEnumerator() as IEnumerator<ObjectPermissionSet>;
        }

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return objectPermissionSets.GetEnumerator();
        }

        #endregion
    }
}
